package ace.cmp.i18n.webmvc.core.impl;

import ace.cmp.i18n.api.AceLocaleResolver;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Locale;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AbstractLocaleResolver;

/**
 * @author caspar
 * @date 2023/8/10 11:15 从header中获取国际化信息
 */
public class DefaultLocaleResolver extends AbstractLocaleResolver implements AceLocaleResolver {
  private final LocaleResolver localeResolver;

  public DefaultLocaleResolver(LocaleResolver localeResolver) {
    this.localeResolver = localeResolver;
    this.setDefaultLocale(Locale.CHINA);
  }

  @Override
  public Locale resolveLocale() {
    ServletRequestAttributes servletRequestAttributes =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (servletRequestAttributes == null) {
      return this.getDefaultLocale();
    }
    HttpServletRequest request = servletRequestAttributes.getRequest();
    return localeResolver.resolveLocale(request);
  }

  @Override
  public Locale resolveLocale(HttpServletRequest request) {
    return localeResolver.resolveLocale(request);
  }

  @Override
  public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    this.localeResolver.setLocale(request, response, locale);
  }
}
